from typing import Optional
from sqlalchemy.orm import Session
from .models import Community, CommunityDyn
from sqlalchemy import desc


def get_by_name(*, db: Session, name: str) -> Optional[Community]:
    return db.query(Community).filter(Community.name == name).one_or_none()


def create(*, db: Session, community_in: dict[str, str]) -> Community:
    community = Community(**community_in)
    db.add(community)
    db.commit()
    return community


def create_dyn(*, db: Session, community_in: dict[str, str], community: Community) -> CommunityDyn:
    community_dyn_dict = {
        k: v for k, v in community_in.items()
        if k in ["three_month_sell_count", "month_see", "sell_count", "followed_num"]
    }
    community_dyn = CommunityDyn(**community_dyn_dict, community_id=community.id)
    db.add(community_dyn)
    db.commit()
    return community_dyn


def update(*, db: Session, community_in: dict[str, str], community: Community) -> Community:
    db_data = community.dict()

    for field in db_data:
        if field in community_in:
            setattr(community, field, community_in[field])

    db.commit()
    return community


def get_previous_dyn(*, db: Session, community: Community) -> Optional[CommunityDyn]:
    community_dyns = (db.query(CommunityDyn).
                      filter(CommunityDyn.community_id == community.id).
                      order_by(desc(CommunityDyn.created_at)).
                      limit(2).all())
    if len(community_dyns) > 1:
        return community_dyns[1]
    else:
        return None
